package com.hrcx.mystery.utils.quartz;

import com.hrcx.mystery.pojo.EbMysteryScheduleJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.concurrent.*;

/**
 * @author hzy
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

    private final ExecutorService service = new ThreadPoolExecutor(10, 15, 30, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());

    @Override
    protected void executeInternal(JobExecutionContext context) {
        EbMysteryScheduleJob scheduleJob = (EbMysteryScheduleJob) context.getMergedJobDataMap().get(EbMysteryScheduleJob.JOB_PARAM_KEY);
        //任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = service.submit(task);
            future.get();
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            //任务执行结果
            log.info("任务执行成功，任务ID：{}，总共耗时：{} 毫秒", scheduleJob.getJobId(), times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：{}", scheduleJob.getJobId(), e);
        }
    }

}
